﻿/****************************************************************
 * Copyright (c) 2010-2013 Besture All Rights Reserved.
 * 
 * File Name:		AdminUserDac 
 * 
 * Created:		2013-6-25 11:43:06
 * Original Author:	nitao 
 * 
 * ------------------------------------------------------------
 * MODIFICATION HISTORY
 * ------------------------------------------------------------
 * When			Who		Why
 * ------------------------------------------------------------
 * 
 *
 ****************************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using Besture.Common;
using Besture.Dal;
using Besture.Model;

namespace Besture.Bll
{
    public class AdminUserDac : BaseFacade
    {
        private readonly AdminUserDal _adminUserDal = new AdminUserDal();
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginName">用户登录名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool Login(string loginName, string password)
        {
            var flag = false;
            try
            {
                // create the connection to the database
                CreateConnection();
                if (_adminUserDal.Login(loginName, password))
                {
                    _adminUserDal.UpdateLastLoginTime(loginName);
                    AdminUserService.Login(loginName);
                    flag = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
            return flag;
        }

        /// <summary>
        /// 修改最后登录时间
        /// </summary>
        /// <param name="LoginName"></param>
        /// <returns></returns>
        public int UpdateLastLoginTime(string LoginName)
        {
            try
            {
                // create the connection to the database
                CreateConnection();
                BeginTransaction();
                int iTmp = _adminUserDal.UpdateLastLoginTime(LoginName);
                if (iTmp > 0)
                {
                    Commit();
                    return iTmp;
                }
                // return no record
                else
                {
                    RollBack();
                    return -1;
                }
            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
        }

        /// <summary>
        /// 修改密码 
        /// </summary>
        /// <param name="LoginName">登录名</param>
        /// <param name="oldPassword">原密码</param>
        /// <param name="password">新密码</param>
        /// <returns>1：修改成功 2：原密码不正确 -1：修改失败</returns>
        public int UpdatePassword(string LoginName, string oldPassword, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(LoginName))
                {
                    return -1;
                }
                // create the connection to the database
                CreateConnection();
                BeginTransaction();
                //判断原密码是否正确
                bool passwordFlag = _adminUserDal.Login(LoginName, oldPassword);
                if (!passwordFlag)
                {
                    return 2;
                }
                //修改密码
                int iTmp = _adminUserDal.UpdatePassword(LoginName, password);
                if (iTmp > 0)
                {
                    _adminUserDal.UpdateLastLoginTime(LoginName);
                    Commit();
                    return iTmp;
                }
                // return no record
                else
                {
                    RollBack();
                    return -1;
                }
            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public bool IsExists(string loginName)
        {
            var flag = false;
            try
            {
                // create the connection to the database
                CreateConnection();
                flag = _adminUserDal.IsExists(loginName);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
            return flag;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns>-1:添加失败 -2:用户名已经存在</returns>
        public int Add(AdminUserModel model)
        {
            try
            {
                // create the connection to the database
                CreateConnection();
                BeginTransaction();
                //判断用户名是否存在
                var existsFlag = _adminUserDal.IsExists(model.LoginName);
                //不存在
                if (!existsFlag)
                {
                    int identityId = _adminUserDal.Add(model);
                    if (identityId > 0)// return only one record
                    {
                        Commit();
                        return identityId;
                    }
                    // return no record
                    else
                    {
                        RollBack();
                        return -1;
                    }
                }
                else
                {
                    return -2;
                }

            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(AdminUserModel model)
        {
            try
            {
                // create the connection to the database
                CreateConnection();
                BeginTransaction();
                int iTmp = _adminUserDal.Update(model);
                if (iTmp > 0)
                {
                    Commit();
                    return iTmp;
                }
                // return no record
                else
                {
                    RollBack();
                    return -1;
                }
            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
        }

        /// <summary>
        /// 单条删除数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(int id)
        {
            try
            {
                // create the connection to the database
                CreateConnection();
                BeginTransaction();
                int iTmp = _adminUserDal.Delete(id);
                if (iTmp > 0)
                {
                    Commit();
                    return iTmp;
                }
                // return no record
                else
                {
                    RollBack();
                    return -1;
                }
            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                CloseConnection();
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public int DeleteList(string ids)
        {
            try
            {
                CreateConnection();
                return _adminUserDal.DeleteList(ids);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                CloseConnection();
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="idList"> </param>
        /// <returns></returns>
        public void DeleteList(List<int> idList)
        {
            try
            {
                // create the connection to the database
                CreateConnection();
                BeginTransaction();
                _adminUserDal.DeleteList(idList);
                Commit();
            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                CloseConnection();
            }
        }

        /// <summary>
        /// 获取用户实例
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AdminUserModel GetModel(int id)
        {
            AdminUserModel model = null;
            try
            {
                // create the connection to the database
                CreateConnection();
                // get the rating and weight data
                IList<AdminUserModel> iList = _adminUserDal.GetModel(id);
                if (iList.Count > 0)
                {
                    model = iList[0];
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
            return model;
        }

        /// <summary>
        /// 获取用户实例
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public AdminUserModel GetModel(string loginName)
        {
            AdminUserModel model = null;
            try
            {
                // create the connection to the database
                CreateConnection();
                // get the rating and weight data
                IList<AdminUserModel> iList = _adminUserDal.GetModel(loginName);
                if (iList.Count > 0)
                {
                    model = iList[0];
                    if (string.IsNullOrEmpty(model.RolesIds)) return model;
                    QueryDal queryDal = new QueryDal();

                    DataTable tablePermissions = queryDal.GetDataTable(string.Format(@"SELECT PERMISSIONS FROM TBRoles t WHERE t.ID IN({0})", model.RolesIds.TrimEnd(',')));


                    string permissions = ConvertString(tablePermissions, "PERMISSIONS");

                    DataTable tablePagePermissions = null;
                    //Admin为超级用户
                    if (model.LoginName.ToLower().Equals("admin"))
                    {
                        tablePagePermissions = queryDal.GetDataTable(string.Format(@"SELECT * FROM TBAdminPages tp ORDER BY tp.SORTID ASC",
                                                            permissions));
                    }
                    else
                    {
                        tablePagePermissions = queryDal.GetDataTable(string.Format(@"SELECT * FROM TBAdminPages tp WHERE tp.ID IN ({0})  ORDER BY tp.SORTID ASC",
                                                          permissions));
                    }

                    //页面权限
                    model.tablePagePermissions = tablePagePermissions;
                    string modulesPermission = ConvertString(tablePagePermissions, "ModulesID");
                    if (!string.IsNullOrEmpty(modulesPermission))
                    {
                        DataTable tableModulesPermissions =
                       queryDal.GetDataTable(string.Format(@"SELECT * FROM TBAdminPages tp WHERE tp.ID IN ({0})  ORDER BY tp.SORTID ASC",
                                                           modulesPermission));
                        model.tableModulesPermissions = tableModulesPermissions;
                    }

                }

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
            return model;
        }


        public string ConvertString(DataTable table, string coulumn)
        {
            string permissionStr = "0,";
            List<string> list = new List<string>();
            foreach (DataRow row in table.Rows)
            {
                if (!string.IsNullOrEmpty(row[coulumn].ToString()) && !list.Contains(row[coulumn].ToString()))
                {
                    list.Add(row[coulumn].ToString());
                }
            }
            foreach (string s in list)
            {
                permissionStr += s + ",";
            }
            return permissionStr.TrimEnd(',');
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataTable(AdminUserModel model)
        {
            try
            {
                // create the connection to the database
                CreateConnection();
                return _adminUserDal.GetDataTable(model);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">password</param>
        /// <returns></returns>
        public int AddUser(string userName, string password)
        {
            try
            {
                CreateConnection();
                BeginTransaction();
                int identityId = _adminUserDal.AddUser(userName, StringHelper.GetMD5(password));
                if (identityId > 0)
                {
                    Commit();
                    return identityId;
                }
                else
                {
                    RollBack();
                    return -1;
                }

            }
            catch (Exception)
            {
                RollBack();
                throw;
            }
            finally
            {
                // close the connection with the database
                CloseConnection();
            }
        }


    }
}
